/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 */
package com.tonann.web.api;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tonann.app.domain.AppDevice;
import com.tonann.app.domain.AppFault;
import com.tonann.app.domain.AppSensor;
import com.tonann.app.service.IAppDeviceService;
import com.tonann.app.service.IAppFaultService;
import com.tonann.app.service.IAppSensorService;
import com.tonann.app.websocket.MsgType;
import com.tonann.app.websocket.SocketMsg;
import com.tonann.app.websocket.WebSocketServer;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.constant.Constants;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.common.core.domain.entity.SysPlace;
import com.tonann.common.core.domain.entity.SysUser;
import com.tonann.common.core.domain.model.LoginUser;
import com.tonann.common.exception.user.UserPasswordNotMatchException;
import com.tonann.common.utils.MessageUtils;
import com.tonann.common.utils.StringUtils;
import com.tonann.framework.manager.AsyncManager;
import com.tonann.framework.manager.factory.AsyncFactory;
import com.tonann.framework.web.service.SysLoginService;
import com.tonann.framework.web.service.TokenService;
import com.tonann.framework.web.service.UserDetailsServiceImpl;
import com.tonann.system.service.ISysPlaceService;
import com.tonann.system.service.ISysUserService;
import com.tonann.web.vo.DeviceVO;
import com.tonann.web.vo.WxUserVO;
import com.tonann.weixin.config.WxMaProperties;
import com.tonann.weixin.domain.WxUser;
import com.tonann.weixin.entity.LoginMaDTO;
import com.tonann.weixin.entity.PhoneDto;
import com.tonann.weixin.entity.WxOpenDataDTO;
import com.tonann.weixin.entity.WxScanDto;
import com.tonann.weixin.model.WXAccessToken;
import com.tonann.weixin.service.IWxUserService;
import com.tonann.weixin.utils.ThirdSessionHolder;
import com.tonann.weixin.utils.WxMaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信用户
 *
 * @author www.joolun.com
 * @date 2019-08-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/wxuser")
@Api(value = "wxuser", tags = "小程序用户API")
public class WxUserApi {

    private final IWxUserService wxUserService;
    private final ISysUserService userService;
    private final TokenService tokenService;
    private final AuthenticationManager authenticationManager;
    private final SysLoginService loginService;
    private final UserDetailsServiceImpl userDetailsService;
    private final IAppDeviceService deviceService;
    private final IAppSensorService sensorService;
    private final ISysPlaceService placeService;
    private final IAppFaultService appFaultService;
    private final RedisTemplate redisTemplate;
    private final WxMaProperties wxMaProperties;

    /**
     * 小程序用户扫描
     *
     * @param scanDto
     * @return
     */
    @ApiOperation(value = "小程序用户扫描")
    @PostMapping("/scan")
    public AjaxResult scan(@RequestBody WxScanDto scanDto) {
        sendMsg("ok", MsgType.INFO, scanDto.getToken());
        System.out.println("收到扫描");
        String sn = "9f68d9ed899c492dbacfd92a07f42756";
        String model_id = "Hwhlj4ySIMTAaK-LW8BPNA";
        PhoneDto phoneDto = new PhoneDto();
        phoneDto.setModelId(model_id);
        phoneDto.setSn(sn);
        cn.hutool.json.JSONObject jsonObject = this.getSnTicket(sn, model_id);
        String snTicket = jsonObject.get("sn_ticket", String.class);
        phoneDto.setSnTicket(snTicket);
        return AjaxResult.success(phoneDto);
    }

    public cn.hutool.json.JSONObject getSnTicket(String sn, String model_id) {
        String ACCESS_TOKEN = null;
        // 微信小程序ID
        String appid = "wx6e420f8197aa9b3d";
        Long startTime = WXAccessToken.getInstance().getGetTime();
        if (startTime == null || System.currentTimeMillis() / 1000 - startTime > 0) {
            cn.hutool.json.JSONObject jsonObject = this.getToken(appid);
            Integer expiresTime = jsonObject.get("expires_in", Integer.class);
            String accessToken = jsonObject.get("access_token", String.class);
            WXAccessToken.getInstance().setWxAccessToken(accessToken);
            WXAccessToken.getInstance().setGetTime(System.currentTimeMillis() / 1000 + expiresTime);
        }
        ACCESS_TOKEN = WXAccessToken.getInstance().getAccessToken();
        String result = null;
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/wxa/getsnticket?access_token=" + ACCESS_TOKEN;
        HashMap<String, Object> requestParam = new HashMap<>();
        // 手机号调用凭证
        requestParam.put("sn", sn);
        requestParam.put("model_id", model_id);
        // 发送post请求读取调用微信接口获取openid用户唯一标识
        String jsonStr = JSONUtil.toJsonStr(requestParam);
        HttpResponse response = HttpRequest.post(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(jsonStr)
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        return JSONUtil.parseObj(result);
    }

    public cn.hutool.json.JSONObject getToken(String appId) {
        String result = null;
        String APPSECRET = null;
        List<WxMaProperties.Config> configs = wxMaProperties.getConfigs();
        if (configs != null) {
            for (WxMaProperties.Config config : configs) {
                String app = config.getAppId();
                if (app.equals(appId)) {
                    APPSECRET = config.getSecret();
                }
            }
        }
        if (APPSECRET == null) {
            return null;
        }
        // 接口调用凭证：accessToken
        String baseUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + APPSECRET;
        HttpResponse response = HttpRequest.get(baseUrl)
                .header(Header.CONTENT_ENCODING, "UTF-8")
                // 发送json数据需要设置contentType
                .header(Header.CONTENT_TYPE, "application/json")
                .execute();
        if (response.getStatus() == HttpStatus.HTTP_OK) {
            result = response.body();
        }
        return JSONUtil.parseObj(result);
    }

    /**
     * 小程序用户登录
     *
     * @param request
     * @param loginMaDTO
     * @return
     */
    @ApiOperation(value = "小程序用户登录")
    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest request, @RequestBody LoginMaDTO loginMaDTO) {
        try {
            WxUser wxUser = wxUserService.loginMa(WxMaUtil.getAppId(request), loginMaDTO.getJsCode());
            WxUserVO vo = new WxUserVO();
            BeanUtils.copyProperties(vo, wxUser);
            if (wxUser.getPhone() != null) {
                List<SysUser> userList = userService.selectUserByPhone(wxUser.getPhone());
                if (userList.size() > 0) {
                    vo.setSysUser(userList.get(0));
                }
            }
            return AjaxResult.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 小程序扫描用户登录
     *
     * @param request
     * @param loginMaDTO
     * @return
     */
    @ApiOperation(value = "小程序扫描用户登录")
    @PostMapping("/loginscan")
    public AjaxResult loginScan(HttpServletRequest request, @RequestBody LoginMaDTO loginMaDTO) throws Exception {
        WxUser wxUser = wxUserService.loginMa(WxMaUtil.getAppId(request), loginMaDTO.getJsCode());
        if (wxUser == null || wxUser.getPhone() == null) {
            sendMsg("无效手机号", MsgType.INFO, loginMaDTO.getSid());
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUser.getNickName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            return AjaxResult.error("无效手机号");
        }
        String phone = wxUser.getPhone();
        List<SysUser> userList = userService.selectUserByPhone(phone);
        if (userList == null || userList.size() == 0) {
            sendMsg("用户不存在", MsgType.INFO, loginMaDTO.getSid());
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUser.getNickName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            return AjaxResult.error("用户不存在");
        } else if (userList.size() > 1) {
            sendMsg("有多个用户", MsgType.INFO, loginMaDTO.getSid());
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUser.getNickName(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            return AjaxResult.error("有多个用户");
        }
        String username = userList.get(0).getUserName();
        try {
            // 该方法会去调用
            LoginUser loginUser = userDetailsService.loadWXUserByUsername(username);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            loginService.recordLoginInfo(loginUser.getUserId());
            // 生成token
            String token = tokenService.createToken(loginUser);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
                put("token", token);
            }};
            sendMsg(JSONObject.toJSONString(authInfo), MsgType.INFO, loginMaDTO.getSid());
            return ajax;
        } catch (Exception e) {
            if (e instanceof UsernameNotFoundException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
        }

        return AjaxResult.error();
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping
    public AjaxResult get() throws Exception {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        WxUserVO vo = new WxUserVO();
        BeanUtils.copyProperties(vo, wxUser);
        if (wxUser.getPhone() != null) {
            List<SysUser> userList = userService.selectUserByPhone(wxUser.getPhone());
            if (userList.size() > 0) {
                vo.setSysUser(userList.get(0));
            }
        }
        return AjaxResult.success(vo);
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取设备信息")
    @GetMapping("/device")
    public AjaxResult getDevice() throws Exception {
        String id = ThirdSessionHolder.getThirdSession().getWxUserId();
        WxUser wxUser = wxUserService.selectWxUserById(id);
        List<AppDevice> deviceList = new ArrayList<>();
        List<DeviceVO> voList = new ArrayList<>();
        SysUser sysUser = null;
//        wxUser.setPhone("15720941205");
        if (wxUser.getPhone() != null) {
            List<SysUser> userList = userService.selectUserByPhone(wxUser.getPhone());
            if (userList.size() > 0) {
                sysUser = userList.get(0);
                deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
            }
        }
        if (sysUser == null) {
            deviceList = deviceService.selectDeviceListIsShow();
        }
        for (AppDevice appDevice : deviceList) {
            DeviceVO vo = new DeviceVO();
            BeanUtils.copyProperties(vo, appDevice);
            List<Long> placeIds = deviceService.selectAppDevicePlaceListByDeviceId(appDevice.getDeviceId());
            String placeName = "";
            for (Long placeId : placeIds) {
                SysPlace place = placeService.selectPlaceById(placeId);
                if (place != null) {
                    placeName += place.getPlaceName();
                }
            }
            vo.setPosition(placeName);
            AppSensor appSensor = new AppSensor();
            appSensor.setDeviceId(appDevice.getDeviceId());
            List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(appDevice.getDeviceId());
            String alarm = "";
            Map<Long, AppFault> faultMap = new HashedMap<>();
            for (AppFault appFault : faultList) {
                AppFault fault = faultMap.get(appFault.getFaultRuleId());
                if (fault == null) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                }
            }
            List<String> alarmList = new ArrayList<>();
            for (Long key : faultMap.keySet()) {
                AppFault fault = faultMap.get(key);
                if (fault != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = simpleDateFormat.format(fault.getCreateTime());
                    alarm += fault.getFaultName() + ":" + dateStr;
                    alarm = vo.getDeviceName() + ":" + alarm;
                    alarmList.add(alarm);
                }
            }
            vo.setAlarmContent(alarmList);
            List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceId(appSensor.getDeviceId());
            List<AppSensor> powerStatusSensorList = new ArrayList<>();
            if (sensorList.size() > 0) {
                for (AppSensor sensor : sensorList) {
//                    AppSensor s = mongoTemplate.findById(sensor.getSensorId(), AppSensor.class);
                    String s = null;
                    Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                    if (object != null){
                        if (object instanceof  String){
                            s = object.toString();
                        }if (object instanceof BigDecimal){
                            s = ((BigDecimal) object).toString();
                        }
                    }
                    if (s != null) {
                        if (sensor.getSensorType().equals("4")) {
                            vo.setAirVolume(s);
                        } else if (sensor.getSensorType().equals("9")) {
                            vo.setAirSpeed(s );
                        } else if (sensor.getUnit().equals("cm") && (sensor.getIsHeight() == null || sensor.getIsHeight().equals("0"))) {
                            vo.setWindowHeight(s );
                        } else if (sensor.getSensorType().equals("13")) {
                            vo.setAngle(s );
                        } else if (sensor.getSensorType().equals("2")) {
                            vo.setHumidity(s );
                        } else if (sensor.getSensorType().equals("1")) {
                            vo.setTemperature(s );
                        } else if (sensor.getSensorType().equals("3")) {
                            vo.setPressure(s );
                        } else if (sensor.getSensorType().equals("6")) {
                            vo.setPowerConsumption(s );
                        } else if (sensor.getSensorType().equals("10")) {
                            vo.setFrequency(s );
                        } else if (sensor.getSensorType().equals("11")) {
                            vo.setAmpere(s );
                        } else if (sensor.getSensorType().equals("16")) {
                            vo.setTvoc(s);
                        } else if (sensor.getSensorType().equals("21")) {
                            vo.setCH2O(s );
                        } else if (sensor.getSensorType().equals("23")) {
                            vo.setO2(s );
                        } else if (sensor.getSensorType().equals("15")) {
                            vo.setNoise(s );
                        } else if (sensor.getSensorType().equals("14")) {
                            vo.setIllumination(s );
                        } else if (sensor.getSensorType().equals("20")) {
                            vo.setCO2(s );
                        } else if (sensor.getSensorType().equals("19")) {
                            vo.setPM1(s );
                        } else if (sensor.getSensorType().equals("18")) {
                            vo.setPM10(s );
                        } else if (sensor.getSensorType().equals("17")) {
                            vo.setPM2Point5(s );
                        } else if (sensor.getSensorType().equals("25")) {
                            vo.setRawWaterConductivity(s );
                        } else if (sensor.getSensorType().equals("26")) {
                            vo.setFirstWaterConductivity(s );
                        } else if (sensor.getSensorType().equals("27")) {
                            vo.setSecondWaterConductivity(s );
                        } else if (sensor.getSensorType().equals("28")) {
                            vo.setLiquidLevel(s );
                        } else if (sensor.getUnit().equals("开关量")) {
                            if (s != null) {
                                if (StringUtils.endsWith(s, ".0")) {
                                    String val = StringUtils.substringBefore(s, ".0");
                                    s = val;
                                }
                            }
                            if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                                vo.setLight(s);
                            } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                                vo.setForce(s);
                            } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                                vo.setPower(s);
                            } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                                vo.setIsAutoDoor(s);
                            } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                                vo.setIsBeing(s);
                            } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                                vo.setWorkingMode(s);
                            }
                        }
                    }
                    if (sensor.getSensorType().equals("24")) {
                        powerStatusSensorList.add(sensor);
                    } else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                        vo.setPower("0");
                        vo.setIsRunning("0");
                        vo.setIsOnline("0");
                    }
                }
            }
            if (powerStatusSensorList.size() > 0) {
                for (AppSensor sensor : powerStatusSensorList) {
                    if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                        if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                            String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                            sensor.setValue(val);
                        }
                        vo.setPower(sensor.getValue());
                    }
                }
            }
            voList.add(vo);
        }
        return AjaxResult.success(voList);
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取设备信息")
    @PostMapping("/deviceWx")
    public AjaxResult getDevice(@RequestBody Long[] ids) {
        List<DeviceVO> voList = new ArrayList<>();
        for (Long deviceId : ids) {
            DeviceVO vo = new DeviceVO();
            vo.setDeviceId(deviceId);
            List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(deviceId);
            String alarm = "";
            Map<Long, AppFault> faultMap = new HashedMap<>();
            for (AppFault appFault : faultList) {
                AppFault fault = faultMap.get(appFault.getFaultRuleId());
                if (fault == null) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                }
            }
            List<String> alarmList = new ArrayList<>();
            for (Long key : faultMap.keySet()) {
                AppFault fault = faultMap.get(key);
                if (fault != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = simpleDateFormat.format(fault.getCreateTime());
                    alarm += fault.getFaultName() + ":" + dateStr;
                    AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(deviceId);
                    if (appDevice != null) {
                        vo.setDeviceName(appDevice.getDeviceName());
                        alarm = vo.getDeviceName() + ":" + alarm;
                    }
                    alarmList.add(alarm);
                }
            }
            vo.setAlarmContent(alarmList);
            List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceId(deviceId);
            List<AppSensor> powerStatusSensorList = new ArrayList<>();
            if (sensorList.size() > 0) {
                for (AppSensor sensor : sensorList) {
//                    AppSensor s = mongoTemplate.findById(sensor.getSensorId(), AppSensor.class);
                    String s = null;
                    Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                    if (object != null){
                        if (object instanceof  String){
                            s = object.toString();
                        }if (object instanceof BigDecimal){
                            s = ((BigDecimal) object).toString();
                        }
                    }
                    if (s != null) {
                        if (sensor.getSensorType().equals("4")) {
                            vo.setAirVolume(s);
                        } else if (sensor.getSensorType().equals("9")) {
                            vo.setAirSpeed(s);
                        } else if (sensor.getUnit().equals("cm") && (sensor.getIsHeight() == null || sensor.getIsHeight().equals("0"))) {
                            vo.setWindowHeight(s);
                        } else if (sensor.getSensorType().equals("13")) {
                            vo.setAngle(s);
                        } else if (sensor.getSensorType().equals("2")) {
                            vo.setHumidity(s);
                        } else if (sensor.getSensorType().equals("1")) {
                            vo.setTemperature(s);
                        } else if (sensor.getSensorType().equals("3")) {
                            vo.setPressure(s);
                        } else if (sensor.getSensorType().equals("6")) {
                            vo.setPowerConsumption(s);
                        } else if (sensor.getSensorType().equals("10")) {
                            vo.setFrequency(s);
                        } else if (sensor.getSensorType().equals("11")) {
                            vo.setAmpere(s);
                        } else if (sensor.getSensorType().equals("16")) {
                            vo.setTvoc(s);
                        } else if (sensor.getSensorType().equals("21")) {
                            vo.setCH2O(s);
                        } else if (sensor.getSensorType().equals("23")) {
                            vo.setO2(s);
                        } else if (sensor.getSensorType().equals("15")) {
                            vo.setNoise(s);
                        } else if (sensor.getSensorType().equals("14")) {
                            vo.setIllumination(s);
                        } else if (sensor.getSensorType().equals("20")) {
                            vo.setCO2(s);
                        } else if (sensor.getSensorType().equals("19")) {
                            vo.setPM1(s);
                        } else if (sensor.getSensorType().equals("18")) {
                            vo.setPM10(s);
                        } else if (sensor.getSensorType().equals("17")) {
                            vo.setPM2Point5(s);
                        } else if (sensor.getSensorType().equals("25")) {
                            vo.setRawWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("26")) {
                            vo.setFirstWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("27")) {
                            vo.setSecondWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("28")) {
                            vo.setLiquidLevel(s);
                        } else if (sensor.getUnit().equals("开关量")) {
                            if (s != null) {
                                if (StringUtils.endsWith(s, ".0")) {
                                    String val = StringUtils.substringBefore(s, ".0");
                                    s = val;
                                }
                            }
                            if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                                vo.setLight(s);
                            } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                                vo.setForce(s);
                            } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                                vo.setPower(s);
                            } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                                vo.setIsAutoDoor(s);
                            } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                                vo.setIsBeing(s);
                            } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                                vo.setWorkingMode(s);
                            }
                        }
                    }
                    if (sensor.getSensorType().equals("24")) {
                        powerStatusSensorList.add(sensor);
                    } else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                        vo.setPower("0");
                        vo.setIsRunning("0");
                        vo.setIsOnline("0");
                    }
                }
            }
            if (powerStatusSensorList.size() > 0) {
                for (AppSensor sensor : powerStatusSensorList) {
                    if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                        if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                            String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                            sensor.setValue(val);
                        }
                        vo.setPower(sensor.getValue());
                    }
                }
            }
            voList.add(vo);
        }
        return AjaxResult.success(voList);
    }


    /**
     * 更新用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "更新用户信息")
    @PutMapping
    public AjaxResult put(@RequestBody WxUser wxUser) throws Exception {
        WxUserVO vo = new WxUserVO();
        BeanUtils.copyProperties(vo, wxUser);
        wxUserService.updateWxUser(wxUser);
        List<SysUser> userList = userService.selectUserByPhone(wxUser.getPhone());
        if (userList.size() > 0) {
            SysUser sysUser = userList.get(0);
            vo.setSysUser(sysUser);
        }
        return AjaxResult.success(vo);
    }

    /**
     * 保存用户信息
     *
     * @param wxOpenDataDTO
     * @return
     */
    @ApiOperation(value = "保存用户信息")
    @PostMapping
    public AjaxResult saveOrUpdateWxUser(@RequestBody WxOpenDataDTO wxOpenDataDTO) {
        wxOpenDataDTO.setAppId(ThirdSessionHolder.getThirdSession().getAppId());
        wxOpenDataDTO.setUserId(ThirdSessionHolder.getThirdSession().getWxUserId());
        wxOpenDataDTO.setSessionKey(ThirdSessionHolder.getThirdSession().getSessionKey());
        WxUser wxUser = wxUserService.saveOrUpdateWxUser(wxOpenDataDTO);
        return AjaxResult.success(wxUser);
    }

    private void sendMsg(String msg, MsgType msgType, String sid) {
        try {
            WebSocketServer.sendInfo(new SocketMsg(msg, msgType), sid);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
